<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\yperp\model;

use app\yperp\common\ChanghongList;
use app\yperp\common\ExcelTools;
use app\yperp\common\Redis;
use app\yperp\job\MgtJob;
use app\yperp\job\MgtJobImage;
use app\yperp\job\MgtJobType;
use app\yperp\job\MgtUpdateJob;
use think\Db;
use think\Model as ThinkModel;
use think\Queue;

/**
 * 广告分类模型
 * @package app\yperp\model
 */
class Supplier extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'yperp_supplier';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    const STATUS_UPLOAD = 0;
    const STATUS_PUSH_WAIT = 1;
    const STATUS_PUSH_SUCCESS = 2;
    const STATUS_SELL = 3;

    const STATUS = [
        0 => '导入',
        1 => '待推',
        2 => '已推',
        3 => '出售',
    ];

    static public function builderSetp($info)
    {
       
    }

    static public function builderUpdateAllSetp($info)
    {
        // 数据根线推送
        $goods_main_img = getGoodsImages('goods_main_img', $info);

        $info['goods_main_img'] = $goods_main_img;

        // goods_header_imgs
        $goods_header_imgs = getGoodsImages('goods_header_imgs', $info);

        array_unshift($goods_header_imgs, $goods_main_img);
        $info['goods_header_imgs'] = $goods_header_imgs;

        // goods_body_imgs
        $info['goods_body_imgs'] = getGoodsImages('goods_body_imgs', $info);

        $array = array_merge([], ChanghongList::login());
        // $array = array_merge($array, ChanghongList::list());
        $array = array_merge($array, ChanghongList::nav());
        $array = array_merge($array, ChanghongList::checkIsset($info));
        $array = array_merge($array, ChanghongList::saveGoodsMainImgs($info));

        $array = array_merge($array, ChanghongList::saveGoodsHeaderImgs($info));
        $array = array_merge($array, ChanghongList::saveGoodsBodyImgs($info));
        $array = array_merge($array, ChanghongList::closeWindow());
        $array = array_merge($array, ChanghongList::checkPushOk($info));
        return $array;
    }

    static public function builderImageSetp($info)
    {

        $goods_main_img = getGoodsImages('goods_main_img', $info);

        $info['goods_main_img'] = $goods_main_img;

        // goods_header_imgs
        $goods_header_imgs = getGoodsImages('goods_header_imgs', $info);

        array_unshift($goods_header_imgs, $goods_main_img);
        $info['goods_header_imgs'] = $goods_header_imgs;

        // goods_body_imgs
        $info['goods_body_imgs'] = getGoodsImages('goods_body_imgs', $info);

        $array = array_merge([], ChanghongList::login());
        // $array = array_merge($array, ChanghongList::list());
        $array = array_merge($array, ChanghongList::nav(['有品超市', '有品生鲜', '蛋类']));
        $array = array_merge($array, ChanghongList::checkIsset($info));
        $array = array_merge($array, ChanghongList::saveGoodsMainImgs($info));
        $array = array_merge($array, ChanghongList::saveGoodsHeaderImgs($info));
        $array = array_merge($array, ChanghongList::closeWindow());
        $array = array_merge($array, ChanghongList::checkPushOk($info));

        // dump($array);die;
        // $array = array_merge($array, [['type' => 'class', 'do' => ['className' =>  'app\yperp\model\Supplier', 'func' => 'status', 'args' => [$info['id'], '1']], 'sleep' => 3],]);
        return $array;
    }
    static public function status($id, $status)
    {
        self::where('id', $id)->update(['status' => $status]);
    }

    static public function test($id, $status)
    {
        dump(['id' => $id, 'status' => $status]);
    }


    static public function uploadfile($goods_imgs_file = null)
    {

        $file_path =  env('root_path') . 'public' . DIRECTORY_SEPARATOR .  get_file_path($goods_imgs_file);

        $goods_code = get_file_name($goods_imgs_file);

        // 删除文件后缀名（假设后缀名是以点号开头，后跟一个或多个字母）
        $goods_code = preg_replace('/\.\w+$/', '', $goods_code);

        $goods_code = Pinyin('permalink', $goods_code, '_');

        $extractToDir = env('root_path') . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'goods' . DIRECTORY_SEPARATOR . $goods_code;

        isdir($extractToDir);

        // 打开 ZIP 文件
        $zipFile = new \PhpZip\ZipFile();
        $zipFile->openFile($file_path); // open archive from file

        $listFiles = $zipFile->getListFiles();
        $zip_one_dir =    explode('/', $listFiles[0])[0];

        $zipFile->extractTo($extractToDir); // extract files to the specified directory
        $zipFile->close();

        moveFilesToDirectory($extractToDir . DIRECTORY_SEPARATOR . $zip_one_dir, $extractToDir);
        rmdir($extractToDir . DIRECTORY_SEPARATOR . $zip_one_dir);

        // 遍历数组中的每个文件名
        $excelFiles = '';
        foreach ($listFiles as $file) {
            // 使用字符串函数检查文件扩展名
            if (strpos($file, '.xls') !== false || strpos($file, '.xlsx') !== false) {
                // 如果文件名包含 .xls 或 .xlsx，则添加到结果数组中
                $excelFiles = $extractToDir . DIRECTORY_SEPARATOR . $file;
            }
        }

        $excelFiles = str_replace(DIRECTORY_SEPARATOR . $zip_one_dir, '', $excelFiles);

        return [$excelFiles, $goods_code];
    }

    static public function saveData($goods_imgs_file)
    {
        list($excelFiles, $goods_code) = self::uploadfile($goods_imgs_file);

        $datas = ExcelTools::getData($excelFiles, 0, 1, [
            'corp_name' => '供应商名称',
            'goods_code' => '资料编码',
            'goods_title' => '商品名称',
            'goods_title_alias' => '商品名称',
            'goods_color' => '颜色',
            'goods_color_alias' => '颜色',
            'goods_color_id' => '颜色id',
            'goods_specs' => '规格',
            'goods_sku' => '商品编码',
            'goods_sku_alias' => '商品编码别名',
            'goods_in_price' => '供货价',
            'goods_buy_price' => '零售价',
            'goods_retail_price' => '分销控价',
            'goods_buy_number' => '库存',
        ]);
        // // 启动事务
        Db::startTrans();
        try {

            foreach ($datas as $key => $data) {
                $corp_name =    $data['corp_name'];
                unset($data['corp_name']);
                $corp =  Db::name('yperp_corp')->where(['corp_name' => $corp_name])->find();
                if (!$corp) {
                    Db::name('yperp_corp')->insert(['corp_name' => $corp_name]);
                }

                $data['goods_color_id'] = $key + 1;

                $where = [
                    'corp_id' => $corp['id'],
                    'goods_code' => $data['goods_code'],
                    'goods_sku' => $data['goods_sku'],
                ];

                $data['goods_code_alias'] = $goods_code;


                $data['goods_sku_alias'] = 'csmb_' . strTools($data['goods_sku']);


                $isset = Db::name('yperp_supplier')->where($where)->find();
                if ($isset) {
                    self::where(['id' => $isset['id']])->update($data);
                } else {
                    self::create($data);
                }
            }

            // 提交事务
            Db::commit();

            return true;
        } catch (\Throwable $th) {
            Db::rollback();
            dump($th->getMessage());
            dump($th->getTraceAsString());
            return false;
        }
    }

    static function push($ids)
    {

        $res = [];
        foreach ($ids as $id) {

            $res[] = Queue::push(MgtJob::class, $id);
        }

        return $res;
    }


    /**
     * 检测状态
     * @param $ids
     * @return array
     * @author 蔡伟明 <314013107@qq.com>
     */
    static function pushUpdate($ids)
    {
        $res = [];
        foreach ($ids as $id) {
            $res[] = Queue::push(MgtUpdateJob::class, $id);
        }
        return $res;
    }


    /**
     * 检测状态
     * @param $ids
     * @return array
     * @author 蔡伟明 <314013107@qq.com>
     */
    static function pushImage($ids)
    {
        $res = [];
        foreach ($ids as $id) {
            $res[] = Queue::push(MgtJobImage::class, $id);
        }
        return $res;
    }


    /**
     * 检测状态
     * @param $ids
     * @return array
     * @author 蔡伟明 <314013107@qq.com>
     */
    static function checkStatus($ids)
    {
        return Queue::push(MgtJobType::class, $ids);
    }
}
